#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QTimer>
#include <QTime>
#include <QFile>
#include <QTextStream>
#include <QByteArray>
#include <iostream>
#include <thread>
#include <chrono>

#include "consts.h"
#include "config.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow) {

  ui->setupUi(this);

  bool success = CreateLessons();
  if (!success) {
    return;
  }

  setWindowTitle("Oh baby~~  just select it ... ");

  QObject::connect(ui->btn_start, &QPushButton::clicked, this, &MainWindow::OnStartClicked);
  QObject::connect(ui->btn_stop, &QPushButton::clicked, this, &MainWindow::OnStopClicked);

  timer_ = new QTimer();
  QObject::connect(timer_, &QTimer::timeout, this, &MainWindow::TimerCallBack);

  QTime time = QTime::currentTime();
  qsrand(time.msec() + time.second() * 1000);
}

MainWindow::~MainWindow() {
  std::for_each(lessons_.begin(), lessons_.end(), [](std::pair<int, Lesson*> l) {
      if (l.second)
          delete l.second;
  });
  delete ui;
}

bool MainWindow::CreateLessons() {
  QFile lesson_file(kLessonFileName.c_str());
  if (!lesson_file.exists()) {
      return false;
  }
  if (!lesson_file.open(QIODevice::ReadOnly | QIODevice::Text)) {
      return false;
  }

  uint32_t l_idx = 0;
  while (!lesson_file.atEnd()) {
      QByteArray array = lesson_file.readLine();
      std::string line = std::string(QString(array).toLocal8Bit());
      Lesson* lesson = new Lesson();
      lesson->name_ = line;
      lessons_.insert(std::make_pair(l_idx++, lesson));
  }
  lesson_file.close();
  lesson_size_ = lessons_.size();
  return true;
}

void MainWindow::OnStartClicked(bool c) {
  if (timer_->isActive()) {
    return;
  }
  timer_->start(kRefreshInterval);
}

void MainWindow::OnStopClicked(bool c) {
  if (timer_->isActive()) {
    timer_->stop();
  }
}

void MainWindow::TimerCallBack() {
  uint r_num = -1;
  while ((r_num = qrand() % lesson_size_) == last_select_);
  std::cout << "last : " << last_select_ << "; current : " << r_num << std::endl;

  if (config_.select_2_full) {
    bool exist = false;
    for (int a : already_) {
      if (a == r_num) {
          exist = true;
          break;
      }
    }
    if (!exist) {
      already_.push_back(r_num);
    } else if (already_.size() == lesson_size_) {
      std::cout << "all have exist !" << std::endl;
      for (int i : already_) {
          std::cout << "exist : " << i << std::endl;
      }
      timer_->stop();
      return;
    }
  }

  std::cout << r_num << std::endl;
  QString name(lessons_[r_num]->name_.c_str());

  ui->lesson_name->setText(name);
  last_select_ = r_num;

}
